<?

$_taglist =		meta('taglist', D_TAGLISTS);
$_catalog =		meta('catalog', 100);

$DATA['tagBaseUrl'] = '/portfolio/';

function tag_search_current($current, $data) {
	if (is_array($data) && sizeof($data)) {
	
		if (array_key_exists($current, $data))
			return array($current => $data[$current]);
		
		foreach($data as $id => $v) {
			if ($t = tag_search_current($current, $v['data'])) {
				$t[$id] = $data[$id];
				return $t;
			}
		}
	}
	
	return false;
}

function tag_apply_filter($data, $filter) {
	$res = array();
	if (is_array($data) && sizeof($data)) {
		
		foreach($data as $id => $v) {
			$res[$id] = $v;
			$res[$id]['filter'] = array_merge((array)$v['filter'], (array)call_user_func_array($filter, array($id, $v)));
			
			if (isset($v['data']) && is_array($v['data']) && sizeof($v['data']))
				if ($t = tag_apply_filter($v['data'], $filter))
					$res[$id]['data'] = $t;
		}
		
		return $res;
	}
	
	return false;
}

//function tags_filter($self, $id, $value) { return array(	
//	'active' => isset($GLOBALS['DATA']['active_tags'][$id])
//	'current' => ((int)param('tag') == $id)
//); }

function tags_filter($id, $value) { 
	return array(	
	'active' => array_key_exists($id, $GLOBALS['DATA']['active_tags']),
	'current' => array_key_exists($id, $GLOBALS['DATA']['current_tags']),
	'theOne' => ((int)param('tag') == $id)
); }


$DATA['active_tags'] = datafetch_array('db_list', array('table' => tb('data, item, x'), 
	'where' => "item.id_parent=$_catalog AND data.id_data=$_taglist AND x.id_link=".X_TAGLISTS." AND x.id1 = item.id AND x.id2 = data.id", 
	'index' => 'id', 'select' => "distinct data.id AS id"));

$DATA['tags'] = datafetch_array('treedata', array('id' => $_taglist, /*'filter' => 'tags_filter',*/ 'order' => 'id_index'));

$DATA['current_tags'] = ($t = (int)param('tag')) ? tag_search_current($t, $DATA['tags']) : array();

$DATA['tags'] = tag_apply_filter($DATA['tags'], 'tags_filter');

//debug($DATA['tags']);

?>